#include <stdio.h>
#include <string.h>
#include "pub_log.h"

struct stCommCmd
{
    int type;
    char buffer[128];	/*信息*/
};
int main(int argc, char *argv[])
{
    fd_set	stReadFds;/*文件描述符*/
    struct  timeval timeout;
    struct	stCommCmd stCmd;
    int		iUdpFd = 0;
    int		iRc = 0;
    int		iTm = 0;
    char line[128];

    memset(&stCmd, 0x00, sizeof(struct stCommCmd));

    iRc = WrLog_init_by_logname_logpath("swman", "./");
    if(iRc < 0)
    {
        fprintf(stderr, "WrLog_init err!\n");
        return -1;
    }

    iUdpFd = udp_bind("swman");
    if( iUdpFd < 0 )
    {
        slog_err("create socket error! iUdpFd=[%d]", iUdpFd);
        WrLog_release();
        return -1;
    }
    while(1)
    {
        iTm = 0;
        write(1, "DHC-Switch> ", strlen("DHC-Switch> "));

        while(1)
        {
            slog_fflush();
            timeout.tv_sec = 30;
            timeout.tv_usec = 0;

            FD_SET(0, &stReadFds);
            iRc = select(3, &stReadFds, NULL, NULL, &timeout);
            if(iRc < 0)
            {
                if(errno == EINTR)
                {
                    slog_info("time interpute");
                    continue;
                }
                else
                {
                    slog_info("select error errno=[%d]", errno, strerror(errno));
                    continue;
                }
            }
            else if(iRc == 0)
            {
                slog_debug("无数据到达,进入下一循环");
                if(iTm > 3)
                {
                    printf("\n用户长时间未操作,swman退出\n");
                    WrLog_release();
                    return 0;
                }
                iTm ++;
                continue;
            }
            else
            {
                break;
            }
        }

        memset(&stCmd, 0x00, sizeof(struct stCommCmd));
        while(gets(stCmd.buffer) == NULL);
        if(strcmp(stCmd.buffer, "stop") == 0)
        {
            stCmd.type = 1;
        }
        iRc = udp_send(iUdpFd, (char *)&stCmd, sizeof(struct stCommCmd), "tcp_lsn");
        if(iRc < 0)
        {
            log_err("udp_send err! errno = [%d][%s]", errno, strerror(errno));
            WrLog_release();
            return -1;
        }
        memset(&stCmd, 0x00, sizeof(struct stCommCmd));
        iRc = udp_recv(iUdpFd, (char *)&stCmd, sizeof(struct stCommCmd));
        if(  iRc < 0 )
        {
            log_err("udp_recv err! errno = [%d][%s]", errno, strerror(errno));
            WrLog_release();
            return -1;
        }
        printf("recv data [%d] [%s]", stCmd.type, stCmd.buffer );
        printf("\n");
    }

    WrLog_release();
    return 0;
}
